package org.dromara.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.demo.domain.BusiForm;
import org.dromara.demo.domain.CargoItem;
import org.dromara.demo.domain.Contact;
import org.dromara.demo.domain.dto.BusiFormDto;
import org.dromara.demo.domain.dto.BusiFormSubmitDto;
import org.dromara.demo.domain.dto.CargoItemDto;
import org.dromara.demo.domain.dto.ContactDto;
import org.dromara.demo.mapper.BusiFormMapper;
import org.dromara.demo.mapper.CargoItemMapper;
import org.dromara.demo.mapper.ContactMapper;
import org.dromara.demo.service.IBusiFormService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 业务表单服务实现类
 */
@Service
public class BusiFormServiceImpl implements IBusiFormService {

    @Autowired
    private BusiFormMapper busiFormMapper;

    @Autowired
    private CargoItemMapper cargoItemMapper;

    @Autowired
    private ContactMapper contactMapper;

    /**
     * 提交业务表单（与前端表单结构对应）
     *
     * @param busiFormSubmitDto 业务表单提交数据传输对象
     * @return 保存的业务表单实体对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BusiForm submitBusiFormFromFrontend(BusiFormSubmitDto busiFormSubmitDto) {
        // 保存业务表单主表信息
        BusiForm busiForm = new BusiForm();
        busiForm.setFormName(busiFormSubmitDto.getName());
        busiForm.setFormDescription(busiFormSubmitDto.getRemark());
        busiForm.setStatus("0"); // 默认正常状态
        busiForm.setRemark("类型: " + busiFormSubmitDto.getType() + 
                          ", 总重量: " + busiFormSubmitDto.getTotalWeight() + 
                          ", 日期时间: " + busiFormSubmitDto.getDateTime());
        busiFormMapper.insert(busiForm);

        // 保存货物明细信息
        if (busiFormSubmitDto.getCargoItems() != null) {
            List<CargoItem> cargoItemList = busiFormSubmitDto.getCargoItems().stream()
                .filter(item -> item.getType() != null && !item.getType().isEmpty() && 
                               item.getWeight() != null && !item.getWeight().isEmpty())
                .map(cargoItemFormDto -> {
                    CargoItem cargoItem = new CargoItem();
                    cargoItem.setFormId(busiForm.getId());
                    cargoItem.setCargoName(cargoItemFormDto.getType());
                    cargoItem.setCargoQuantity(0); // 前端未提供数量
                    try {
                        cargoItem.setCargoWeight(new BigDecimal(cargoItemFormDto.getWeight()));
                    } catch (NumberFormatException e) {
                        cargoItem.setCargoWeight(BigDecimal.ZERO);
                    }
                    cargoItem.setCargoValue(BigDecimal.ZERO); // 前端未提供价值
                    cargoItem.setRemark("来自前端表单提交");
                    return cargoItem;
                })
                .collect(Collectors.toList());
            
            if (!cargoItemList.isEmpty()) {
                cargoItemList.forEach(cargoItemMapper::insert);
            }
        }

        // 保存联系人信息
        if (busiFormSubmitDto.getContacts() != null) {
            List<Contact> contactList = busiFormSubmitDto.getContacts().stream()
                .filter(contact -> contact.getName() != null && !contact.getName().isEmpty() && 
                                  contact.getPhone() != null && !contact.getPhone().isEmpty())
                .map(contactFormDto -> {
                    Contact contact = new Contact();
                    contact.setFormId(busiForm.getId());
                    contact.setContactName(contactFormDto.getName());
                    contact.setContactPhone(contactFormDto.getPhone());
                    contact.setContactEmail(""); // 前端未提供邮箱
                    contact.setContactAddress(contactFormDto.getPosition() != null ? contactFormDto.getPosition() : "");
                    contact.setRemark(contactFormDto.getPrimary() != null && contactFormDto.getPrimary() ? "主要联系人" : "");
                    return contact;
                })
                .collect(Collectors.toList());
            
            if (!contactList.isEmpty()) {
                contactList.forEach(contactMapper::insert);
            }
        }

        return busiForm;
    }

    /**
     * 提交业务表单
     *
     * @param busiFormDto 业务表单数据传输对象
     * @return 保存的业务表单实体对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BusiForm submitBusiForm(BusiFormDto busiFormDto) {
        // 保存业务表单主表信息
        BusiForm busiForm = new BusiForm();
        BeanUtils.copyProperties(busiFormDto, busiForm);
        busiFormMapper.insert(busiForm);

        // 保存货物明细信息
        List<CargoItemDto> cargoItems = busiFormDto.getCargoItems();
        if (cargoItems != null && !cargoItems.isEmpty()) {
            List<CargoItem> cargoItemList = cargoItems.stream().map(cargoItemDto -> {
                CargoItem cargoItem = new CargoItem();
                BeanUtils.copyProperties(cargoItemDto, cargoItem);
                cargoItem.setFormId(busiForm.getId());
                return cargoItem;
            }).filter(cargoItem -> cargoItem.getCargoName() != null && !cargoItem.getCargoName().isEmpty()) // 添加验证
            .collect(Collectors.toList());
            if (!cargoItemList.isEmpty()) {
                cargoItemList.forEach(cargoItemMapper::insert);
            }
        }

        // 保存联系人信息
        List<ContactDto> contacts = busiFormDto.getContacts();
        if (contacts != null && !contacts.isEmpty()) {
            List<Contact> contactList = contacts.stream().map(contactDto -> {
                Contact contact = new Contact();
                BeanUtils.copyProperties(contactDto, contact);
                contact.setFormId(busiForm.getId());
                return contact;
            }).filter(contact -> contact.getContactName() != null && !contact.getContactName().isEmpty() && 
                                contact.getContactPhone() != null && !contact.getContactPhone().isEmpty()) // 添加验证
            .collect(Collectors.toList());
            if (!contactList.isEmpty()) {
                contactList.forEach(contactMapper::insert);
            }
        }

        return busiForm;
    }

    /**
     * 根据ID获取业务表单
     *
     * @param id 业务表单ID
     * @return 业务表单实体对象
     */
    @Override
    public BusiForm getBusiFormById(Long id) {
        return busiFormMapper.selectById(id);
    }

    /**
     * 获取所有业务表单
     *
     * @return 业务表单实体对象列表
     */
    @Override
    public List<BusiForm> getAllBusiForms() {
        return busiFormMapper.selectList();
    }

    /**
     * 根据业务表单ID获取货物明细列表
     *
     * @param busiFormId 业务表单ID
     * @return 货物明细实体对象列表
     */
    @Override
    public List<CargoItem> getCargoItemsByBusiFormId(Long busiFormId) {
        if (busiFormId == null) {
            return List.of(); // 返回空列表而不是null
        }
        // 使用QueryWrapper构建查询条件
        QueryWrapper<CargoItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("form_id", busiFormId);
        // Mapper中已包含按创建时间倒序排列的逻辑
        return cargoItemMapper.selectList(queryWrapper);
    }

    /**
     * 根据业务表单ID获取联系人列表
     *
     * @param busiFormId 业务表单ID
     * @return 联系人实体对象列表
     */
    @Override
    public List<Contact> getContactsByBusiFormId(Long busiFormId) {
        if (busiFormId == null) {
            return List.of(); // 返回空列表而不是null
        }
        // 使用QueryWrapper构建查询条件
        QueryWrapper<Contact> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("form_id", busiFormId);
        // Mapper中已包含按创建时间倒序排列的逻辑
        return contactMapper.selectList(queryWrapper);
    }
}